<template>
    <div class="homework-container">
        <div class="content">
            <div class="homework-title">
                {{homeworkInfo.title}}
            </div>
            <div class="homework-desc">
                {{homeworkInfo.answerContext}}
            </div>
            <div class="homework-files" v-if="homeworkInfo.answerMaterialInfoList&&homeworkInfo.answerMaterialInfoList.length">
                <div class="homework-file" v-for="item in homeworkInfo.answerMaterialInfoList" :key="item.materialId" @click="previewMaterial(item.materialId, item)">
                    <img class="file-icon" :src="imgSrc(item.materialType)" alt="" />
                    <div class="file-info">
                        <div class="file-name">{{item.materialFullName}}</div>
                        <div class="file-size">{{item.materialSizeFormat}}</div>
                    </div>
                </div>
            </div>
        </div>
        <footer>
            <div class="submit-num" v-if="homeworkInfo.times !== -1&&remainingTimes">还可以提交{{remainingTimes}}次</div>
            <van-button v-if="homeworkInfo.times !== -1" type="primary" :disabled="!remainingTimes" @click="edit">{{remainingTimes?'编辑作业':'不可编辑，修改次数已用完'}}</van-button>
            <van-button v-else type="primary" :disabled="!remainingTimes" @click="edit">编辑作业</van-button>
        </footer>
    </div>
</template>

<script setup>
import {isApp} from '@/lib/judge-env.js';
import { preview } from '@yanxiu/player';
import { onMounted, reactive, ref, computed } from 'vue';
import { useRoute } from 'vue-router';
import { useStore } from 'vuex';
import { handleErrorPage } from '@/lib/tools.js';

const emit = defineEmits(['to-reply']);
const route = useRoute();
const store = useStore();

const loading = ref(false);
// 慕课详情数据
const detailData = ref({});
const homeworkInfo = ref({})
const fileTypes = ['audio', 'doc', 'img', 'pdf', 'ppt', 'video', 'xls', 'catalogue', 'edit', 'live', 'evaluate']
const imgs = {
    'audio': require('@/assets/images/file-icons/audio-icon.png'),
    'doc': require('@/assets/images/file-icons/doc-icon.png'),
    'img': require('@/assets/images/file-icons/img-icon.png'),
    'others': require('@/assets/images/file-icons/others-icon.png'),
    'pdf': require('@/assets/images/file-icons/pdf-icon.png'),
    'ppt': require('@/assets/images/file-icons/ppt-icon.png'),
    'video': require('@/assets/images/file-icons/video-icon.png'),
    'xls': require('@/assets/images/file-icons/xls-icon.png'),
    'catalogue': require('@/assets/images/catalogue-icon.png'),
    'edit': require('@/assets/images/file-icons/doc-icon.png'),
    'live': require('@/assets/images/file-icons/live-icon.png'),
    'evaluate': require('@/assets/images/file-icons/evaluate-icon.png'),
}
function imgSrc(str) {
    return fileTypes.indexOf(str) === -1 ? imgs.others: imgs[str]
}
// 有效剩余提交次数
const remainingTimes = computed(() => {
    let allTimes = homeworkInfo.value?.times || 0;
    let answerTimes = homeworkInfo.value?.answerTimes || 0;
    return allTimes - answerTimes
})
const brandInfo = computed(() => {
    return store.state.brand?.publishBrand;
})
// 获取作业详情
function getHomeworkInfo () {
    if (!route.params.homeworkId) {
        return false;
    }
    loading.value = true;
    G_transmit('homeworkInfo', {
        queries: {
            homeWorkId: route.params.homeworkId
        }
    }).then((res) => {
        homeworkInfo.value = res?.data || {};
        homeworkInfo.value.title = res?.data?.homeWorkAnswerVO?.title || '';
        homeworkInfo.value.answerContext = res?.data?.homeWorkAnswerVO?.context || '';
        homeworkInfo.value.answerMaterialInfoList = res?.data?.homeWorkAnswerVO?.answerMaterialInfoList || [];
    }).finally(() => {
        loading.value = false;
    })
}

// 获取课程详情
async function getCourseDetail() {
    try {
        let res = await G_transmit('moocDetail', {
            queries: {
                id: route.params.moocId
            },
            silence: true
        })

        detailData.value = res.data || {};

        // 不是购买者 并且不是创建人
        let notCourseUser = !detailData.value?.isBuy && !detailData.value?.isMyCreate;

        let isPublish = detailData.value?.publishState == 1 && detailData.value?.state == 4;

        // 课程未发布 除创建人和已经报名的人都不能看
        if (!isPublish && notCourseUser) {
            handleErrorPage('unpublished', route.params.moocId);
        }
        // 慕课发布了 除创建人和已经报名的人都不能看
        if(notCourseUser) {
            handleErrorPage('notsignup', route.params.moocId);
        }
        getHomeworkInfo();
    } catch(_err) {
        // 禁用课程 30800500 删除课程 30800404
        if (_err.status && _err.status.code && [30800500, 30800404].includes(_err.status.code)) {
            handleErrorPage('delete', route.params.moocId);
        }  else {
            G_dispatchEvent('toast', { message: _err?.status?.desc || '服务开小差了～', type: 'error'});
        }
    }
}

const edit = () => {
    store.dispatch('jsBridge/disposeBridge', {
        method: 'goNewPage',
        url: {
            name: 'answerHomework',
            params: {
                moocId: route.params.moocId,
                homeworkId: route.params.homeworkId
            }
        },
        naviBarHidden: false
    })
}

let previewVm = null;

const previewMaterial = (id, item) => {
    let type = typeFn(item.materialType);
    let appUrl = item.previewUrl || item.materialUrl;
    if (!appUrl || type === '') {
        Toast.fail('抱歉，该文件暂不支持预览');
        return;
    }
    if (isApp()) {
        setTimeout(() => {
            store.dispatch('jsBridge/SXYJSBridge', {
                method: 'previewMedia',
                data: {
                    type: type,
                    url: appUrl,
                    materialId: item.materialId,
                    dtBrandId:brandInfo.value.brand
                }
            });
        }, 77);
    } else {
        preview(item.materialVo, {
            mode: 'h5'
        }).then((vm) => {
            previewVm = vm;
        });
    }
};

const typeFn = (type) => {
    switch (type) {
        case 'audio':
            return 3;
        case 'video':
            return 2;
        case 'img':
            return 1;
        case 'doc':
        case 'xls':
        case 'ppt':
        case 'pdf':
            return 4;
        default:
            return '';
    }
};
onMounted(() => {
    store.dispatch('jsBridge/disposeBridge', {
        method: 'setNativeTitle',
        options: {
            title: route.meta.title,
            showBack: true
        }
    });
    getCourseDetail();
});
</script>
<style lang="scss" scoped>
.homework-container {
    min-height: 100vh;
    padding-bottom: 130px;
    background: #ffffff;
    .content {
        padding: 15px;
        font-family: PingFangSC-Regular, PingFang SC;
        .homework-title {
            font-size: 14px;
            font-family: PingFangSC-Semibold, PingFang SC;
            font-weight: 600;
            color: #171A1D;
            line-height: 22px;
            word-break: break-word;
            padding-bottom: 15px;
            border-bottom: 1px solid #E0E2E4;
        }
        .homework-desc {
            font-size: 13px;
            font-weight: 400;
            color: #171A1D;
            line-height: 22px;
            word-break: break-word;
            margin-top: 15px;
        }
    }
    footer {
        width: 100%;
        position: fixed;
        left: 0;
        bottom: 0;
        background: #ffffff;
        padding: 8px 15px;
        padding-bottom: calc(constant(safe-area-inset-bottom) + 15px);
        padding-bottom: calc(env(safe-area-inset-bottom) + 15px);
        box-shadow: 0px -4px 6px 0px rgba(140,149,179,0.08);
        .submit-num {
            font-size: 13px;
            font-weight: 400;
            color: #FF9201;
            line-height: 20px;
            text-align: center;
            margin: 2px 0 10px;
        }
        .van-button {
            width: 100%;
            height: 44px;
            border-radius: 4px;
            background-color: #0084F6;
            font-size: 16px;
        }
    }
}
.homework-files {
    margin-top: 15px;
    .homework-file {
        height: 64px;
        background: #F5F5F5;
        border-radius: 2px;
        display: flex;
        align-items: center;
        padding: 0 15px;
        margin-bottom: 10px;
        .file-icon {
            width: 28px;
            height: 32px;
        }
        .file-info {
            width: 0;
            flex: 1;
            margin-left: 8px;
            .file-name {
                font-size: 14px;
                font-weight: 400;
                color: #171A1D;
                line-height: 22px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            }
            .file-size {
                font-size: 12px;
                font-weight: 400;
                color: #A2A3A4;
                line-height: 18px;
                margin-top: 4px;
            }
        }
    }
}
</style>
